<template>
  <div class="video-add">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- 视频标题 -->
      <el-form-item label="视频标题" prop="video_title">
        <el-input v-model="form.video_title" placeholder="请输入视频标题" />
      </el-form-item>

      <!-- 视频描述 -->
      <el-form-item label="视频描述" prop="video_desc">
        <el-input
          v-model="form.video_desc"
          type="textarea"
          :rows="20"
          :autosize="{ minRows: 20, maxRows: 40 }"
          placeholder="请输入视频描述"
          resize="none"
        />
      </el-form-item>

      <!-- 视频来源链接 -->
      <el-form-item label="微信视频" prop="video_wxurl">
        <el-input v-model="form.video_wxurl" placeholder="请输入微信视频播放地址" />
      </el-form-item>

      <el-form-item label="抖音视频" prop="video_dyurl">
        <el-input v-model="form.video_dyurl" placeholder="请输入抖音视频播放地址" />
      </el-form-item>

      <el-form-item label="快手视频" prop="video_ksurl">
        <el-input v-model="form.video_ksurl" placeholder="请输入快手视频播放地址" />
      </el-form-item>

      <!-- 美食地点 -->
      <el-form-item label="美食地点" prop="location">
        <div class="location-container">
          <el-select
            v-model="form.province"
            placeholder="请选择省份"
            class="location-select"
            filterable
            clearable
            @change="handleProvinceChange"
          >
            <el-option
              v-for="(name, code) in provinceData"
              :key="code"
              :label="name"
              :value="code"
            />
          </el-select>

          <el-select
            v-model="form.city"
            placeholder="请选择城市"
            :disabled="!form.province"
            class="location-select"
            filterable
            clearable
            @change="handleCityChange"
          >
            <el-option
              v-for="(name, code) in cityData"
              :key="code"
              :label="name"
              :value="code"
            />
          </el-select>

          <el-select
            v-model="form.district"
            placeholder="请选择区县"
            :disabled="!form.city"
            class="location-select"
            filterable
          >
            <el-option
              v-for="(name, code) in districtData"
              :key="code"
              :label="name"
              :value="code"
            />
          </el-select>
        </div>
        <el-input
          v-model="form.detailAddress"
          placeholder="请输入详细地址"
          style="margin-top: 10px"
        />
      </el-form-item>

      <!-- 美食店铺 -->
      <el-form-item label="美食店铺" prop="video_shop">
        <el-input
          v-model="form.video_shop"
          placeholder="请输入美食店铺名称"
        />
      </el-form-item>

      <!-- 来源纪录片 -->
      <el-form-item label="来源纪录片" prop="video_produccer">
        <el-input v-model="form.video_produccer" placeholder="请输入来源纪录片" />
      </el-form-item>

      <!-- 视频封面 -->
      <el-form-item label="视频封面" prop="video_coverimg">
        <el-upload
          class="cover-uploader"
          :action="`${domain}/upload/img`"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :headers="headers"
        >
          <img v-if="form.video_coverimg" :src="form.video_coverimg" class="cover-image">
          <i v-else class="el-icon-plus cover-uploader-icon" />
        </el-upload>
        <div class="cover-tip">建议尺寸：800x450px，支持 jpg、png 格式</div>
      </el-form-item>

      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">发布</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { pca, pcaa } from 'area-data'
import { addVideo } from '@/api/videoapi'

export default {
  name: 'VideoAdd',
  data() {
    return {
      domain: process.env.VUE_APP_DOMAIN || 'http://localhost:6688',
      form: {
        video_title: '',
        video_desc: '',
        video_wxurl: '',
        video_dyurl: '',
        video_ksurl: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        video_produccer: '',
        video_shop: '',
        video_coverimg: ''
      },
      rules: {
        video_title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        video_desc: [
          { required: false, message: '请输入视频描述', trigger: 'blur' }
        ],
        video_wxurl: [
          { required: true, message: '请输入微信视频地址', trigger: 'blur' }
        ],
        video_dyurl: [
          { required: false, message: '请输入抖音视频地址', trigger: 'blur' }
        ],
        video_ksurl: [
          { required: false, message: '请输入快手视频地址', trigger: 'blur' }
        ],
        video_produccer: [
          { required: true, message: '请输入来源纪录片', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        video_shop: [
          { required: true, message: '请输入美食店铺名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        video_coverimg: [
          { required: true, message: '请上传视频封面', trigger: 'change' }
        ]
      },
      provinceData: pca['86'],
      cityData: {},
      districtData: {},
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      isCompressing: false
    }
  },
  methods: {
    handleProvinceChange(provinceCode) {
      this.form.city = ''
      this.form.district = ''
      this.cityData = pca[provinceCode] || {}
      this.districtData = {}
    },
    handleCityChange(cityCode) {
      this.form.district = ''
      this.districtData = pcaa[cityCode] || {}
    },

    getFullAddress() {
      const province = this.provinceData[this.form.province] || ''
      const city = this.cityData[this.form.city] || ''
      const district = this.districtData[this.form.district] || ''
      return `${province}${city}${district}${this.form.detailAddress}`
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const fullAddress = this.getFullAddress()
          const formData = {
            ...this.form,
            video_address: fullAddress,
            province: this.provinceData[this.form.province] || '',
            city: this.cityData[this.form.city] || '',
            district: this.districtData[this.form.district] || '',
            location: {
              province: this.provinceData[this.form.province] || '',
              city: this.cityData[this.form.city] || '',
              district: this.districtData[this.form.district] || '',
              detail: this.form.detailAddress,
              shop: this.form.video_shop
            }
          }

          addVideo(formData).then(res => {
            if (res.code === 20000) {
              this.$message.success('视频添加成功')
              this.resetForm(formName)
              this.$router.push({
                path: '/videos/list',
                params: { refresh: true }
              })
            } else {
              this.$message.error(res.message || '视频添加失败')
            }
          }).catch(error => {
            this.$message.error(error.message || '视频添加失败')
          })
        }
        return false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.cityData = {}
      this.districtData = {}
      this.form.video_address = ''
      this.form.video_shop = ''
      this.form.video_coverimg = ''
    },

    handleCoverSuccess(res) {
      if (res.code === 20000) {
        this.form.video_coverimg = res.data.url
        this.$message.success('封面上传成功')
      } else {
        this.$message.error(res.message || '封面上传失败')
      }
    },

    async compressImage(file) {
      try {
        this.isCompressing = true
        this.$loading({
          lock: true,
          text: '图片压缩中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return await new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = (e) => {
            const img = new Image()
            img.src = e.target.result
            img.onload = () => {
              const canvas = document.createElement('canvas')
              const ctx = canvas.getContext('2d')
              const width = img.width
              const height = img.height
              canvas.width = width
              canvas.height = height
              ctx.drawImage(img, 0, 0, width, height)

              const tryCompress = (quality = 0.9) => {
                canvas.toBlob((blob) => {
                  if (blob.size <= 80 * 1024 || quality <= 0.1) {
                    resolve(new File([blob], file.name, {
                      type: 'image/jpeg',
                      lastModified: Date.now()
                    }))
                  } else {
                    tryCompress(quality - 0.1)
                  }
                }, 'image/jpeg', quality)
              }
              tryCompress()
            }
            img.onerror = (err) => reject(err)
          }
          reader.onerror = (err) => reject(err)
        })
      } finally {
        this.isCompressing = false
        this.$loading().close()
      }
    },

    async beforeCoverUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt80KB = file.size <= 80 * 1024

      if (!isImage) {
        this.$message.error('封面图片只能是 JPG 或 PNG 格式!')
        return false
      }

      if (!isLt80KB) {
        try {
          const compressedFile = await this.compressImage(file)
          if (compressedFile.size <= 80 * 1024) {
            return compressedFile
          } else {
            this.$message.error('压缩后图片仍然超过 80KB，请选择更小的图片!')
            return false
          }
        } catch (error) {
          this.$message.error('图片压缩失败，请重试!')
          return false
        }
      }

      return isImage && isLt80KB ? file : false
    }
  }
}
</script>

<style lang="scss" scoped>
.video-add {
  padding: 20px;

  // 添加文本框样式
  :deep(.el-textarea__inner) {
    line-height: 1.5;
    padding: 10px;
    font-size: 14px;
  }
}
.location-container {
  display: flex;
  gap: 10px;
}
.location-select {
  width: 120px;
}
.el-textarea,
.el-select {
  width: 100%;
}

.cover-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409EFF;
    }
  }
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.cover-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.cover-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
